import {
    _decorator,
    animation,
    Animation,
    AnimationClip,
    Component,
    Node,
    resources,
    Sprite,
    SpriteFrame,
    UITransform,
} from "cc";
import { TILE_HEIGHT, TILE_WIDTH } from "../Scene/TileManager";
import { SPIKES_TYPE_MAP_TOTAL_COUNT_ENUM, ENTITY_TYPE_ENUM, PARAMS_NAME_ENUM, EVENT_TYPE } from "../../Enums";
import { ISpikes } from "../../Levels";
import { randomIdByLen } from "../../Utils";
import { StateMachine } from "../../Base/StateMachine";
import { SpikesStateMachine } from "./SpikesStateMachine";
import EventManager from "../../Runtime/EventManager";
import DataManager from "../../Runtime/DataManager";
const { ccclass, property } = _decorator;

@ccclass("SpikesManager")
export class SpikesManager extends Component {
    id: string = randomIdByLen(12);

    x: number = 0;
    y: number = 0;
    fsm: StateMachine;
    type: ENTITY_TYPE_ENUM;

    private _count: number;
    private _totalCount: number;


    get count() {
        return this._count;
    }

    set count(newCount: number) {
        this._count = newCount;
        this.fsm.setParams(PARAMS_NAME_ENUM.SPIKES_CUR_COUNT, newCount);
    }

    get totalCount() {
        return this._totalCount;
    }

    set totalCount(newTotalCount: number) {
        this._totalCount = newTotalCount;
        this.fsm.setParams(PARAMS_NAME_ENUM.SPIKES_TOTAL_COUNT, newTotalCount);
    }

    async init(params: ISpikes) {
        const sprite = this.addComponent(Sprite);
        sprite.sizeMode = Sprite.SizeMode.CUSTOM;

        const transform = this.getComponent(UITransform);
        transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4);

        this.fsm = this.addComponent(SpikesStateMachine);
        await this.fsm.init();

        this.x = params.x;
        this.y = params.y;

        this.type = params.type;

        this.count = params.count;
        this.totalCount = SPIKES_TYPE_MAP_TOTAL_COUNT_ENUM[params.type];

        EventManager.Instance.on(EVENT_TYPE.PLAYER_MOVE_END, this.onLoop, this);
    }

    protected onDestroy(): void {
        EventManager.Instance.off(EVENT_TYPE.PLAYER_MOVE_END, this.onLoop);
    }

    update() {
        this.node.setPosition(this.x * TILE_WIDTH - TILE_WIDTH * 1.5, -this.y * TILE_HEIGHT + TILE_HEIGHT * 1.5);
    }

    onLoop() {
        if (this.count === this.totalCount) {
            this.count = 1;
        } else {
            this.count += 1;
        }

        this.attachPlayer();
    }

    backZero() {
        this.count = 0;
    }

    attachPlayer() {
        if (!DataManager.Instance.player) {
            return;
        }

        const { x: playerX, y: playerY } = DataManager.Instance.player;
        if (this.x === playerX && this.y === playerY && this.count === this.totalCount) {
            EventManager.Instance.emit(EVENT_TYPE.ATTACH_PLAYER, PARAMS_NAME_ENUM.AIR_DEATH);
        }
    }
}
